package cn.ekgc.system.service.impl;


import cn.ekgc.system.dao.UserInfoDao;
import cn.ekgc.system.pojo.dto.MenuTreeDto;
import cn.ekgc.system.service.UserInfoService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张翰林
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoDao userInfoDao;

    @Override
    public List<MenuTreeDto> getInfoById(Long id) {
        List<MenuTreeDto> infoById = userInfoDao.getInfoById(id);
        List<MenuTreeDto> fatherMenu = infoById
                //steam().filter 是进行筛选 当父菜单id = 0时
                .stream()
                .filter(ml -> ml.getParentId() == 0).toList();
        //进行调用查找子菜单
        return getInfoChild(fatherMenu, infoById);
    }

    //查找子菜单
    private List<MenuTreeDto> getInfoChild(List<MenuTreeDto> data, List<MenuTreeDto> menu) {
        //存储树结构的菜单树
        ArrayList<MenuTreeDto> tree = new ArrayList<>();
        // 封装树结构菜单数据
        data.forEach(md -> {
            //封装的MenuTree树结构对象
            MenuTreeDto ml = new MenuTreeDto();
            //前一个是源对像，后一个是目标对象
            BeanUtils.copyProperties(md, ml);
            //遍历目录和菜单找出子菜单并封装子菜单
//                        List<MenuTreeDto> childs = new ArrayList<>();
//                        menu.forEach(m -> {
//                                if (m.getParentId() != null) {
//                                        if (m.getParentId()==(ml.getId())) {
//                                                childs.add(m);
//                                        }
//                                }
//                        });
            List<MenuTreeDto> childs = menu.stream().filter(
                    m -> m.getParentId().equals(md.getId())
            ).toList();
            if (!childs.isEmpty()) {
                ml.setChildMenu(getInfoChild(childs, menu));
            }
            tree.add(ml);
        });
        return tree;
    }
}